//
//  EMMyOrderViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/27.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMMyOrderViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMOrderCell.h"
#import "EMSegmentedControl.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "EMOrderReqBody.h"
#import "EMOrderRespBody.h"
#import "EMOrderInfo.h"
#import "EMGoodInfo3.h"
#import "UIImageView+WebCache.h"
#import "EMDoCommonViewController.h"
#import "EMCheckOrderOtherReqBody.h"
#import "EMGetFetchShopRespBody.h"
#import "EMCheckOrderAddressRespBody.h"
#import "EMCheckOrderPostInfoRespBody.h"
#import "UserInfo.h"
@interface EMMyOrderViewController ()
{
    AppDelegate *app;
    NSArray *orderList;
    UITableView *messageTable;
}
@end

@implementation EMMyOrderViewController
- (void)hideBottomBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
            view.hidden = YES;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    orderList = [NSArray array];
    [self hideBottomBar];
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"我的订单";
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [self getOrderInfoWithMode:@"1"];
}
- (void)backAction: (UIButton *)sender
{
    self.navigationController.navigationBar.barTintColor = RGB(255, 255, 255);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGB(242, 242, 242);
    
    EMSegmentedControl *segment = [[EMSegmentedControl alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 30)];
    [segment setTitleArray:@[@"全部订单", @"配送订单", @"自取订单"]];
    [segment setActionBlock:^(NSUInteger index) {
        switch (index) {
            case 0:
                [self getOrderInfoWithMode:@"1"];
                [messageTable reloadData];
                break;
            case 1:
                [self getOrderInfoWithMode:@"2"];
                [messageTable reloadData];
                break;
            case 2:
                [self getOrderInfoWithMode:@"3"];
                [messageTable reloadData];
                break;
            default:
                break;
        }
    }];
    [self.view addSubview:segment];

    messageTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 94) style:UITableViewStylePlain];
    messageTable.delegate = self;
    messageTable.dataSource = self;
    [self.view addSubview:messageTable];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return orderList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[section]];
    return orderInfo.m_orderGoodList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"myOrderCell";
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[indexPath.section]];
    EMGoodInfo3 *goodInfo = [[EMGoodInfo3 alloc] initWithOrderGoodInfo:orderInfo.m_orderGoodList[indexPath.row]];

    EMOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[EMOrderCell alloc] initWithFrame:CGRectZero];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.goodNameLabel.text = goodInfo.m_name;
    cell.goodDescLabel.text = (NSNull *)goodInfo.m_goodDesc == [NSNull null] ? @"" : goodInfo.m_goodDesc;;
    if ([goodInfo.m_mode isEqualToString:@"0"]) {
        cell.nowPriceLabel.text = [NSString stringWithFormat:@"¥%@", goodInfo.m_nowPrice];
        cell.originPriceLabel.text = @"";
    } else {
        cell.nowPriceLabel.text = [NSString stringWithFormat:@"¥%@", goodInfo.m_nowPrice];
        NSMutableAttributedString *oPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@", goodInfo.m_originPrice]];
        [oPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, goodInfo.m_originPrice.length+1)];
        cell.originPriceLabel.attributedText = oPrice;
    }
    
    [cell.goodImgView sd_setImageWithURL:[NSURL URLWithString:goodInfo.m_imgUrl]];
    cell.commonButton.tag = 20000 + indexPath.section * 100 + indexPath.row;
    [cell.commonButton addTarget:self action:@selector(doCommom:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 35;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[section]];
    
    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width-20, 30)];
    headerView.backgroundColor = RGB(133, 150, 81);
    headerView.text = [NSString stringWithFormat:@"   %@    订单号:%@    订单状态:%@", orderInfo.m_orderTime, orderInfo.m_orderNumber, [self converseToOrderState:orderInfo.m_orderState]];
    headerView.textColor = [UIColor whiteColor];
    headerView.font = [UIFont fontWithName:HEITILIGHT size:11];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width-30, 35)];
    cell.backgroundColor = [UIColor whiteColor];
    
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[section]];
    if ([orderInfo.m_orderGetway isEqualToString:@"1"]) {
        UIButton *checkAddress = [UIButton buttonWithType:UIButtonTypeCustom];
        checkAddress.frame = CGRectMake(W(120), 0, W(80), H(25));
        checkAddress.backgroundColor = [UIColor greenColor];
        checkAddress.layer.cornerRadius = 5;
        [checkAddress setTitle:@"查询自取店铺" forState:UIControlStateNormal];
        checkAddress.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
        checkAddress.tag = 30000 + section;
        [checkAddress addTarget:self action:@selector(checkFetchAddress:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:checkAddress];
    } else {
        UIButton *checkAddress = [UIButton buttonWithType:UIButtonTypeCustom];
        checkAddress.frame = CGRectMake(W(50), 0, W(80), H(25));
        checkAddress.backgroundColor = [UIColor greenColor];
        checkAddress.layer.cornerRadius = 5;
        [checkAddress setTitle:@"查看收获地址" forState:UIControlStateNormal];
        checkAddress.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
        checkAddress.tag = section + 33000;
        [checkAddress addTarget:self action:@selector(checkOrderAddress:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:checkAddress];
        
        UIButton *checkPostInfo = [UIButton buttonWithType:UIButtonTypeCustom];
        checkPostInfo.frame = CGRectMake(W(190), 0, W(80), H(25));
        checkPostInfo.backgroundColor = [UIColor greenColor];
        checkPostInfo.layer.cornerRadius = 5;
        [checkPostInfo setTitle:@"查看配送信息" forState:UIControlStateNormal];
        checkPostInfo.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
        checkPostInfo.tag = section + 36000;
        [checkPostInfo addTarget:self action:@selector(checkOrderPostInfo:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:checkPostInfo];
    }
    
    UIView *gray = [[UIView alloc] init];
    gray.frame = CGRectMake(0, 30, W(320), 15);
    gray.backgroundColor = [UIColor lightGrayColor];
    [cell addSubview:gray];
    return cell;
}
- (NSString *)converseToOrderState:(NSString *)orderStateNum
{
    switch ([orderStateNum intValue]) {
        case 0:
            return @"未付款";
            break;
        case 1:
            return @"已付款";
            break;
        case 2:
            return @"确认订单";
            break;
        case 3:
            return @"配送中";
            break;
        case 4:
            return @"已完成";
            break;
        default:
            return @"";
            break;
    }
}

- (void)doCommom:(UIButton *)sender
{
    NSLog(@"%ld", sender.tag);
    
    NSInteger section = (sender.tag - 20000) / 100;
    NSInteger row = (sender.tag - 20000) % 100;
    
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[section]];
    EMGoodInfo3 *goodInfo = [[EMGoodInfo3 alloc] initWithOrderGoodInfo:orderInfo.m_orderGoodList[row]];
    
    EMDoCommonViewController *controller = [[EMDoCommonViewController alloc] init];
    controller.orderNumber = orderInfo.m_orderNumber;
    controller.goodInfo = goodInfo;
    [self.navigationController pushViewController:controller animated:YES];
    
}

- (void)checkFetchAddress: (UIButton *)sender
{
    NSInteger index = sender.tag - 30000;
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[index]];
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMCheckOrderOtherReqBody *reqBody = [[EMCheckOrderOtherReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"ORDER-GET-SHOP";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ORDERNO = orderInfo.m_orderNumber;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMGetFetchShopRespBody *respBody = [EMGetFetchShopRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            NSString *alertString = [NSString stringWithFormat:@"自取店铺:%@\n店铺地址:%@", respBody.SHOPNAME, respBody.SHOPADDRESS];
            [app showAlert:alertString];
            
        } else {
            
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}

- (void)checkOrderAddress: (UIButton *)sender
{
    NSInteger index = sender.tag - 33000;
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[index]];
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMCheckOrderOtherReqBody *reqBody = [[EMCheckOrderOtherReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"ORDER-SHIPPING-ADDRESS";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ORDERNO = orderInfo.m_orderNumber;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMCheckOrderAddressRespBody *respBody = [EMCheckOrderAddressRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            NSString *alertString = [NSString stringWithFormat:@"地址:%@%@%@%@\n收货人:%@\n手机:%@", respBody.PRONAME, respBody.CITYNAME, respBody.CITYNAME, respBody.ADDRESS, respBody.NAME, respBody.PHONE];
            [app showAlert:alertString];
            
        } else {
            
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}


- (void)checkOrderPostInfo: (UIButton *)sender
{
    NSInteger index = sender.tag - 36000;
    EMOrderInfo *orderInfo = [[EMOrderInfo alloc] initWithOrderInfo:orderList[index]];
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMCheckOrderOtherReqBody *reqBody = [[EMCheckOrderOtherReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"ORDER-PS-INFO";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ORDERNO = orderInfo.m_orderNumber;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMCheckOrderPostInfoRespBody *respBody = [EMCheckOrderPostInfoRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            NSString *alertString = [NSString stringWithFormat:@"配送人姓名:%@\n配送人手机:%@", respBody.PSNAME, respBody.PSTEL];
            [app showAlert:alertString];
            
        } else {
            
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}

- (void)getOrderInfoWithMode:(NSString *)mode
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMOrderReqBody *reqBody = [[EMOrderReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"USER-ORDER-INFO";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.SIGN = mode;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMOrderRespBody *respBody = [EMOrderRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            orderList = respBody.ORDERINFO;
            
        } else {
            
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    

}
@end
